<template>
  <div v-loading="formLoading" class="bg">
    <div class="btns routeHeader mb-5px">
        <el-button
        @click="submitForm(1)"
        :loading="formLoading"
        type="primary"
        v-hasPermi="['salary:accounting-mend-work-monad:save']"
        v-if="!btnStatus || [10,40].includes(formData.dictMendWorkMonadStatus)"
      >
        保存
      </el-button>
      <el-button
        type="primary"
        @click="submitForm(2)"
        :loading="formLoading"
        v-hasPermi="['salary:accounting-mend-work-monad:update']"
        v-if="query.type == 'create' || (query.type == 'update' && [10,40].includes(formData.dictMendWorkMonadStatus))"
      >
        提交
      </el-button>
      <el-button
        type="primary"
        @click="submitForm(3)"
        :loading="formLoading"
        v-hasPermi="['salary:accounting-mend-work-monad:pass']"
        v-if="query.type == 'update' && [20,30].includes(formData.dictMendWorkMonadStatus) "
      >
        通过
      </el-button>
      <el-button
        type="danger"
        @click="submitForm(4)"
        :loading="formLoading"
        v-hasPermi="['salary:accounting-mend-work-monad:noPass']"
        v-if="query.type == 'update' && [20,30].includes(formData.dictMendWorkMonadStatus)"
      >
        不通过
      </el-button> 
      <el-button @click="goBack"> 关闭 </el-button>
    </div>
    <div class="formView" :style="`height: ${contentHeight}px`">
          <div class="logoBox">
            <img src="@/assets/imgs/hasColorLogo.png" alt="" class="logo" />
            <div class="logoTitleBox">
              <div class="logoTitle">江苏江顺精密机电设备有限公司</div>
              <div ><span style="font-size:14px">补工单</span></div>
            </div>
          </div>
          <div class="firstCard">
            <el-row class="colItem">
              <el-col :span="8" class="cardItem">
                <div class="formTitle"><span style="color:red">*</span>任务下达时间</div>
                 <el-date-picker
                   v-model="taskIssuedDate"
                   value-format="YYYY-MM-DD"
                   type="daterange"
                   start-placeholder="开始日期"
                   end-placeholder="结束日期"
                   style="flex:1;height:50px"
                   :disabled="query.type=='view'"
                 />
              </el-col>
              <el-col :span="8" class="cardItem" style="display:flex">
                <div class="formTitle" >
                  <div class="formTitle"><span style="color:red">*</span>工时类型</div>
                </div>
                <el-select
                  v-model="formData.manHourType"
                  placeholder="请选择工时类型"
                  clearable
                  filterable
                  remote
                  reserve-keyword
                  :remote-method="getManHourTypeList"
                  @change="selectManHourType"
                  style="flex:1"
                  :disabled="query.type=='view'"
                >
                <el-option
                  v-for="item in manHourTypeOptions"
                  :key="item.id"
                  :label="item.manHourType"
                  :value="item.manHourType"
                />
        </el-select>
              </el-col>
              <el-col :span="8" class="cardItem">
                <div class="formTitle">补工单号</div>
                <el-input v-model="formData.mendWorkNumber" disabled/>
              </el-col>
            </el-row>
            <el-row class="colItem">
              <el-col :span="24" class="cardItem" style="align-items: center">
                <div class="formTitle"><span style="color:red">*</span>员工名称</div>
                <!-- <el-input v-model="formData.staffMes" /> -->
                <div style="margin:0 10px 0 10px"><el-button type="primary" @click="openStaffDialog">选择员工</el-button></div>
                <div v-for="(item, index) in firstTenTags" :key="index" class="spanbox">
                <div v-if="item">
                <span class="tagspan">{{ item.staffName }}</span>
                <i class="span_close" @click="removeTag(index)"></i>
                </div>
              </div>
             <div v-if="remainingTagsStatus" class="spanbox remainingTags">
                <span class="tagspan"> ...... </span>
             </div>   
              </el-col>
            </el-row>
            <el-row class="colItem">
              <el-col :span="8" class="cardItem">
                <div class="formTitle">产品编号</div>
                <el-input v-model="formData.productNumber" :disabled="query.type=='view'"/>
              </el-col>
              <el-col :span="8" class="cardItem">
                <div class="formTitle">图号</div>
                <el-input v-model="formData.drawingNumber" :disabled="query.type=='view'"/>
              </el-col>
              <el-col :span="8" class="cardItem">
                <div class="formTitle">材质</div>
                <el-input v-model="formData.material" :disabled="query.type=='view'"/>
              </el-col>
            </el-row>
            <el-row class="colItem">
              <el-col :span="8" class="cardItem">
                <div class="formTitle">工序号</div>
                <el-input v-model="formData.operationNumber" :disabled="query.type=='view'"/>
              </el-col>
              <el-col :span="8" class="cardItem">
                <div class="formTitle">工序名</div>
                <el-input v-model="formData.operationName" :disabled="query.type=='view'"/>
              </el-col>
              <el-col :span="8" class="cardItem">
                <div class="formTitle">定额工时</div>
                <el-input v-model="formData.quotaManHour" :disabled="query.type=='view'" @input="validateInput('quotaManHour')" />
              </el-col>
            </el-row>
            <el-row class="colItem">
              <el-col :span="8" class="cardItem">
                <div class="formTitle">任务数量</div>
                <el-input v-model="formData.taskQuantity" :disabled="query.type=='view'" @input="validateInput('taskQuantity')"/>
              </el-col>
              <el-col :span="8" class="cardItem">
                <div class="formTitle">加工数量</div>
                <el-input v-model="formData.processQuantity" :disabled="query.type=='view'" @input="validateInput('processQuantity')"/>
              </el-col>
              <el-col :span="8" class="cardItem">
                <div class="formTitle">合格数量</div>
                <el-input v-model="formData.qualifiedQuantity" :disabled="query.type=='view'" @input="validateInput('qualifiedQuantity')"/>
              </el-col>
            </el-row>
            <el-row class="colItem">
              <el-col :span="24" class="cardItem">
                <div class="formTitle">备注</div>
                <el-input v-model="formData.remark" :disabled="query.type=='view'"/>
              </el-col>
            </el-row>
            <el-row class="colItem">
              <el-col :span="24" class="cardItem">
                <div class="formTitle"><span style="color:red">*</span>日有效工时</div>
                <el-input v-model="formData.skyVaildManHour" @input="validateInput('skyVaildManHour')" :disabled="query.type=='view'"/>
              </el-col>
            </el-row>
            <el-row class="colItem">
              <el-col :span="24" class="cardItem">
                <div class="formTitle">调度员意见</div>
                <el-input v-model="formData.yardmanOpinion" :disabled="formData.dictMendWorkMonadStatus !=20 || query.type=='view'" />
              </el-col>
            </el-row>
            <el-row class="colItem">
              <el-col :span="24" class="cardItem">
                <div class="formTitle">检验员意见</div>
                <el-input v-model="formData.inspectorOpinion" :disabled="formData.dictMendWorkMonadStatus !=30|| query.type=='view'" />
              </el-col>
            </el-row>
          </div>
    </div>
  </div>
<!-- 选择员工 -->
<staffDialog ref="staffDialogRef" @setStaff="setStaff" />
</template>
<script setup>
import * as AccountingMendWorkMonadApi from '@/api/payroll/shopWagesCalculate/accountingMendWorkMonad'
import * as WageManHourValuationApi from '@/api/config/wageManHourValuation'
import { useTagsViewStore } from '@/store/modules/tagsView'
import staffDialog from './staffDialog.vue'
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formData = ref({})
const contentHeight = ref(0)
const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
let manHourTypeOptions = ref() //工时类型
let taskIssuedDate = ref([])//任务时间
//远程获取工时类型
const getManHourTypeList = async (query) =>{
  let res = await WageManHourValuationApi.getWageManHourValuationPage({
    pageNo: 1,
    pageSize: 10,
    dictManHourValuationStatus: 10,
    manHourType:query
  })
  manHourTypeOptions.value = res.list
}

//选中工时类型，获取工时计价单价
const selectManHourType = (val)=>{
  manHourTypeOptions.value.forEach((item)=>{
    console.log('item',item)
    if(item.manHourType==val){
      formData.value.unitPrice = item.unitPrice
    }
  })
}

// 选择员工
const staffDialogRef = ref()
const openStaffDialog  = ()=>{
  if(query.type=='view') return
  staffDialogRef.value.open(jobNumberList.value)
}

// 设置员工
const firstTenTags  =ref([])
const remainingTags =ref([])
const remainingTagsStatus =ref(false)
const jobNumberList =ref([])
const setStaff = ()=>{
  const staffMes = staffDialogRef.value.multipleSelection
  let jobNumberListTemp =[]
  let firstTenTagsTemp =[]
  let remainingTagsTemp =[]
  staffMes.forEach((item)=>{
      jobNumberListTemp.push(item.jobNumber)
      jobNumberList.value = jobNumberListTemp
    if(firstTenTags.value.length <=10){
      firstTenTagsTemp.push({
        staffName:item.staffName,
        jobNumber:item.jobNumber
      })
      firstTenTags.value=firstTenTagsTemp
    }else{
      remainingTagsTemp.push({
        staffName:item.staffName,
        jobNumber:item.jobNumber
      })
      remainingTags.value=remainingTagsTemp
      remainingTagsStatus.value = true
    }
  })
}

//删除tag
const removeTag =(index)=>{
  console.log(firstTenTags.value,"firstTenTags.value")
 if(firstTenTags.value){
  firstTenTags.value.splice(index,1)
  jobNumberList.value.splice(index,1)
 }
 if(remainingTags.value.length>0){
  let tags = remainingTags.value.shift()
  firstTenTags.value.push(tags)
 }
 if(remainingTags.value.length==0){
  remainingTagsStatus.value = false
 }
}

let inputVal = ref([])
// 只能填写数字，允许小数点后 2位数
const validateInput = (val) => {
 // 只允许数字和小数点
  formData.value[val] = formData.value[val].replace(/[^\-?\d.]/g, ''); 
  const decimalParts =  formData.value[val].split('.');
  if(inputVal.value.indexOf(val)==-1)inputVal.value.push(val)
  if(decimalParts[0] == '')formData.value[val] = ''
if(val=="skyVaildManHour"){
  //只允许在首位输入-负号
  const minusParts = formData.value[val].split('');
  minusParts.forEach((item,index)=>{
    if(minusParts[index+1]=='-'){
      minusParts.splice(index+1,1)
    }
    formData.value[val] = minusParts.join('')
  })
  if (decimalParts.length > 2) { 
  // 如果小数点出现多次，只保留第一个小数点之前的部分和小数点后的部分
  formData.value[val] = decimalParts[0] + '.' + decimalParts[1]
} else if (decimalParts[1] && decimalParts[1].length > 2) {
  // 如果小数部分超过2位，不允许继续输入
  formData.value[val] = decimalParts[0] + '.' + decimalParts[1].slice(0, 2)
}
}
};

/**返回 */
const tagsViewStore = useTagsViewStore()
const route = useRouter() // 路由
const goBack = async () => {
  //获取当前路由并删除tagView
  tagsViewStore.delView(route.currentRoute.value)
  //跳转列表页
  route.push({
    path: '/payroll/payroll/shopWagesCalculate/accountingMendWorkMonad'
  })
}

//提交/保存
const submitForm = async (num) =>{
  console.log('formData.value',formData.value)
  formData.value.submitFlag = num
  console.log(remainingTags.value,'remainingTags.value')
  if(remainingTags.value.length !=0){
    formData.value.staffList = (firstTenTags.value.concat(remainingTags.value))
  }else{
    formData.value.staffList = firstTenTags.value
  }
  
  let temp = []
  console.log('formData.value.staffList',formData.value.staffList)
  formData.value.staffList.forEach((item)=>{
    console.log(item,"45454545")
    temp.push(item.staffName)
  })
  formData.value.staffName = temp.join(",")
  if(taskIssuedDate.value){
    formData.value.taskBeginIssuedDate = taskIssuedDate.value[0]
    formData.value.taskEndIssuedDate = taskIssuedDate.value[1]
  }
  inputVal.value.forEach((item)=>{
    formData.value[item] = parseFloat(formData.value[item]);
  })
  console.log(formData.value,'formData.value')
  let check = ['',null,undefined]
  if(
    check.indexOf(formData.value.taskBeginIssuedDate) !=-1 ||
    check.indexOf(formData.value.taskEndIssuedDate) !=-1 ||
    check.indexOf(formData.value.manHourType) !=-1 ||
    check.indexOf(formData.value.staffList)  !=-1 ||
    check.indexOf(formData.value.skyVaildManHour) !=-1 
    ){
      message.warning(t('请输入任务下达时间/工时类型/工时类型'))
      return
  }
  formLoading.value = true
  try {
  if(query.type =='create'){
    await AccountingMendWorkMonadApi.createAccountingMendWorkMonad(formData.value)
    message.success(t('common.createSuccess'))
    goBack()
  }else if(query.type =='update'){
    await AccountingMendWorkMonadApi.updateAccountingMendWorkMonad(formData.value)
    message.success(t('common.updateSuccess'))
  }
  goBack()
  } finally {
    formLoading.value = false
  }
}


const { query } = useRoute() // 路由的查询
const btnStatus =ref(false) //按钮进入的状态
/** 初始化 */
onMounted(async () => {
  contentHeight.value = document.body.clientHeight - 132 - 60
  if(query.type !='create'){
    btnStatus.value = true
    const res = await AccountingMendWorkMonadApi.getAccountingMendWorkMonad(query.id)
    formData.value = res
    taskIssuedDate.value[0]=formData.value.taskBeginIssuedDate
    taskIssuedDate.value[1]=formData.value.taskEndIssuedDate
    let jobNumberListTemp =[]
    let firstTenTagsTemp =[]
    let remainingTagsTemp =[]
    formData.value.operatorSimpleList.forEach((item,index)=>{
      jobNumberListTemp.push(item.jobNumber)
      jobNumberList.value = jobNumberListTemp
      if(index < 9){
        firstTenTagsTemp.push({
        staffName:item.staffName,
        jobNumber:item.jobNumber
      })
      firstTenTags.value=firstTenTagsTemp
    }else {
      remainingTagsTemp.push({
        staffName:item.staffName,
        jobNumber:item.jobNumber
      })
      remainingTags.value=remainingTagsTemp
      remainingTagsStatus.value = true
    }
  })
}
})

</script>
<style lang="scss" scoped>
:deep(.el-input-number) {
  width: 100%;
}
.bg{
  background-color:white;
  padding-top: 10px;
}

::v-deep .upload-file-uploader{
  display: flex;
}

.upLoadFile{
  margin-left: 10px;
 ::v-deep .el-upload-list--text{
    display:flex;
    width:120px;
  }
}
::v-deep .el-select .el-input__inner {
  height:50px;
}
.formView {
  overflow-y: auto;
  padding:50px;
}

.Search{
  display:flex;
}

.btns {
  margin-bottom: 10px;
  padding-left: 10px;
}

.title {
  font-size: 16px;
  font-weight: bold;
  margin: 10px 0 20px;
}

.logoBox{
  display: flex;
  align-items: center;
.logo {
  width: 300px;
  height: 80px;
}
  .logoTitleBox{
  width: 100%;
  display: flex;
  flex-direction: column;
  margin-bottom: 10px;
  padding-right: 250px;
  .logoTitle {
  font-size: 34px;
  text-align: center;
}
:last-child{
  display: flex;
  justify-content: center;
}
}
}

.radioGroup{
  display: flex;
  flex:1;
  justify-content: center;
}
.firstCard {
  border: 1px solid #000;

  :deep(.el-input__wrapper, .el-textarea__inner) {
    box-shadow: 0 0 0 0 var(--el-input-border-color, var(--el-border-color)) inset;
  }

  :deep(.el-textarea__inner) {
    box-shadow: 0 0 0 0 var(--el-input-border-color, var(--el-border-color)) inset;
  }

  .newCardItem {
    border-left: 1px solid #000;
  }

/* 标签 */
.spanbox {
  display: inline-block;
  font-size: 14px;
  margin: 3px 4px 3px 0;
  background-color: #2cc0bc;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);
  height:32px;
  div {
  height:32px;
  display:flex;
  align-items: center;
  i {
    height:32px;
    line-height:32px;
  }
}
}
.remainingTags {
    display:flex;
    justify-content: space-around;
    width:50px;
    .tagspan{
      padding-left:0px;
    }
}
/* 标签文字 */
.tagspan {
  height: 24px;
  line-height: 22px;
  max-width: 99%;
  position: relative;
  display: inline-block;
  padding-left: 8px;
  color: #ffffff;
  font-size: 14px;
  opacity: 1;
  vertical-align: middle;
  overflow: hidden;
  transition: 0.25s linear;
}

/* tag的叉叉 */
.span_close {
  padding: 0 6px 0 4px;
  opacity: 1;
  -webkit-filter: none;
  filter: none;
  color: #ffffff;
  /* font-weight: 600; */
  cursor:pointer;
}
/* 鼠标经过叉叉 */
.span_close:hover{
  color: #e8eaec;
}
.span_close:after {
  content: "\00D7";
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  /* line-height: 27px; */
  transition: 0.3s, color 0s;
}

  .newFormTitle {
    width: 150px;
    height: 36.5px;
    line-height: 32px;
    background: #e9fbfb;
    text-align: center;
    border-right: 1px solid #000;
  }

  .disFlex {
    display: flex;
  }

  .alignCenter {
    align-items: center;
  }

  .top-border {
    border-top: 1px solid #000;
  }

  .colItem + .colItem {
    border-top: 1px solid #000;
  }

  .editType {
    display: flex;
    align-items: center;

    > div {
      width: 14.2857%;
      text-align: center;
    }

    .editTypeTitle {
      background: #e9fbfb;
    }

    > div + div {
      border-left: 1px solid #000;
    }
  }

  .cardItem {
    display: flex;
    line-height: 50px;
    height:50px;

    .formTitle {
      flex-shrink: 0;
      width: 150px;
      height: 100%;
      font-size:16px;
      background: #e9fbfb;
      text-align: center;
      border-right: 1px solid #000;
    }

    .formBigTitle {
      width: 150px;
      flex-shrink: 0;
      line-height: 73px;
      background: #e9fbfb;
      text-align: center;
      border-right: 1px solid #000;
    }
  }

  .cardItem + .cardItem {
    border-left: 1px solid #000;
  }
}
</style>
